package com.deYang.app.ljodfh.ui.fragment;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.widget.CustomCheckBox;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.ruihang.generalibrary.utils.TimeObserve;
import com.deYang.app.ljodfh.R;
import com.deYang.app.ljodfh.base.BaseActivity;
import com.deYang.app.ljodfh.base.BaseFragment;
import com.deYang.app.ljodfh.base.Constances;
import com.deYang.app.ljodfh.beans.FVersionInfo;
import com.deYang.app.ljodfh.http.AbsNetCallBack;
import com.deYang.app.ljodfh.http.NetUtils;
import com.deYang.app.ljodfh.ui.activities.AboutActivity;
import com.deYang.app.ljodfh.ui.activities.HistoriesActivity;
import com.deYang.app.ljodfh.ui.activities.InvitationCodeActivity;
import com.deYang.app.ljodfh.ui.activities.LiveBroadcastActivity;
import com.deYang.app.ljodfh.ui.activities.LoginActivity;
import com.deYang.app.ljodfh.ui.activities.MyAnchorDyActivity;
import com.deYang.app.ljodfh.ui.activities.MyCollectionActivity;
import com.deYang.app.ljodfh.ui.activities.MySubscribeActivity;
import com.deYang.app.ljodfh.ui.activities.ShareAnchorActivity;
import com.deYang.app.ljodfh.ui.activities.UserInfoActivity;
import com.deYang.app.ljodfh.ui.dialog.FontSizeDiaFragment;
import com.deYang.app.ljodfh.ui.dialog.ShowDiaFragment;
import com.deYang.app.ljodfh.ui.utils.GlideCircleTransform;
import com.deYang.app.ljodfh.ui.utils.GlideUtil;
import com.deYang.app.ljodfh.ui.utils.cache.DataCleanManager;
import com.deYang.app.ljodfh.ui.utils.update.DownloadManager;
import com.deYang.app.ljodfh.utils.UserManager;
import com.deYang.app.ljodfh.utils.VersionUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by Administrator on 2017/6/26 0026.
 */
public class MineFragment extends BaseFragment implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {

    private final int REQUEST_CODE_LOGIN = 201;
    private final int REQUEST_CODE_INFO = 202;
    private final int REQUEST_CODE_ANCHOR = 203;
    private final int REQUEST_CODE_INVITATION = 204;
    @BindView(R.id.mine_push_cb)
    protected CustomCheckBox push_cb;
    @BindView(R.id.mine_icon)
    protected ImageView mine_icon;
    @BindView(R.id.mine_username)
    protected CustomFontTextView mine_userName;
    @BindView(R.id.mine_anchor_lay)
    protected LinearLayout anchorLay;
    @BindView(R.id.mine_share_anchor)
    protected LinearLayout shareSchorLay;
    @BindView(R.id.mine_anchor_edit)
    protected LinearLayout anchorEditLay;
    @BindView(R.id.mine_living)
    protected LinearLayout sendLiving;
    @BindView(R.id.mine_login)
    protected LinearLayout login;
    @BindView(R.id.mine_font_size_content)
    protected CustomFontTextView font_tv;
    @BindView(R.id.mine_cache_size)
    protected CustomFontTextView cache_tv;
    @BindView(R.id.title_top_edit)
    protected CustomFontTextView exit_tv;
    //    @BindView(R.id.title_top_back)
//    protected ImageView backImg;
    @BindView(R.id.tv_version)
    protected CustomFontTextView tv_version;

    @BindView(R.id.mine_deivider)
    protected View divider;
    private FontSizeDiaFragment fontSizeDiaFragment;
    private ShowDiaFragment showDiaFragment;
    public static final String FONT_TAG = "dia_font_size_fragment";
    public static final String SHOW_TAG = "dia_show_fragment";

    private DownloadManager manager = null;
    private FVersionInfo versionInfo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        backImg.setVisibility(View.GONE);
        initBuildLay();
        getVersion();
        exit_tv.setText(R.string.quit);
        checkUser();
    }


    boolean isUpdate = false;

    public void getVersion() {
        NetUtils.getNetAdapter().getVersion(getOwnerName(), "sctv/appVersion.json", new AbsNetCallBack<FVersionInfo>(FVersionInfo.class) {
            @Override
            public void onSuc(FVersionInfo fVersionInfo) {
                int versionCode = VersionUtil.getVersionCode(getActivity());
                if (fVersionInfo != null && fVersionInfo.getVersionCode() > versionCode) {
                    isUpdate = true;
                    tv_version.setText("有可用新版本");
                    versionInfo = fVersionInfo;
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            checkUser();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOGIN) {
            if (resultCode == LoginActivity.RESULT_OK) {
                initUser();
            }
        } else if (requestCode == REQUEST_CODE_INFO) {
            initUser();
        } else if (requestCode == REQUEST_CODE_ANCHOR) {
            if (resultCode != 0) {
                checkUser();
            }
        } else if (requestCode == REQUEST_CODE_INVITATION) {
            checkUser();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        TimeObserve.removeObserS(getOwnerName());
    }

    private void initBuildLay() {
        boolean isPush = (boolean) SharedPreferencesUtil.getParam(getContext(), "PUSH_KEY", false);
        if (isPush) {
            push_cb.setChecked(true);
        } else {
            push_cb.setChecked(false);
        }
        push_cb.setOnCheckedChangeListener(this);
        exit_tv.setOnClickListener(this);
    }

    private void initData() {
        try {
            String totalCacheSize = DataCleanManager.getTotalCacheSize(getContext());
            cache_tv.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkUser() {
        checkFontSize();
        if (UserManager.getInstance().isLogin()) {
            initUser();
        } else {
            mine_userName.setText(R.string.login_or_register);
            mine_icon.setImageResource(R.mipmap.icon_circle_avatar);
            exit_tv.setVisibility(View.GONE);
            anchorLay.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
            sendLiving.setVisibility(View.GONE);
        }
    }

    /**
     * 调用前需检查非空
     */
    private void initUser() {
        mine_userName.setText(UserManager.getInstance().getUser().getNickName());
        String icon = UserManager.getInstance().getUser().getAvatar();
        if (!TextUtils.isEmpty(icon)) {
            GlideUtil.getDynamicGlid(getContext(), icon, true).transform(new GlideCircleTransform(getContext()))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(mine_icon);
        }
        int type = UserManager.getInstance().getUser().getUserType();
        if (type == Constances.USER_TYPE_ANCHOR) {
            anchorLay.setVisibility(View.GONE);
            sendLiving.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
        }
        if (type == Constances.USER_TYPE_REPORTER) {
            anchorLay.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
            sendLiving.setVisibility(View.GONE);
        }
        exit_tv.setVisibility(View.VISIBLE);
    }

    private void checkFontSize() {
        int fontSize = (int) SharedPreferencesUtil.getParam(getActivity(), Constances.FONT_KEY, Constances.SMALL_FONT);
        if (fontSize == Constances.BIG_FONT) {
            font_tv.setText("大");
        } else if (fontSize == Constances.MID_FONT) {
            font_tv.setText("中");
        } else if (fontSize == Constances.SMALL_FONT) {
            font_tv.setText("小");
        }
    }

    @OnClick({R.id.mine_living, R.id.mine_share_anchor, R.id.mine_font_size, R.id.mine_anchor_edit})
    public void itemClick(View view) {
        switch (view.getId()) {
            case R.id.mine_living:
                Intent intent = new Intent(getContext(), LiveBroadcastActivity.class);
                startActivity(intent);
                break;
            case R.id.mine_share_anchor:
                Intent shareIntent = new Intent(getContext(), ShareAnchorActivity.class);
                startActivityForResult(shareIntent, REQUEST_CODE_ANCHOR);
                break;
            case R.id.mine_font_size:
                showFontDialog();
                break;
            case R.id.mine_anchor_edit:
                Intent anchorEdit = new Intent(getContext(), MyAnchorDyActivity.class);
                startActivity(anchorEdit);
                break;
        }
    }

    @OnClick({R.id.mine_clean_cache, R.id.mine_check_newVersion, R.id.mine_about, R.id.mine_telephone_ll})
    public void mineClick(View view) {
        switch (view.getId()) {
            case R.id.mine_clean_cache:
                showProgress("正在清理缓存...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        DataCleanManager.clearAllCache(getActivity());
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    toast(getString(R.string.mine_cache_success));
                                    String size = DataCleanManager.getTotalCacheSize(getActivity());
                                    cache_tv.setText(size);
                                    closeProgress();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }).start();

                break;
            case R.id.mine_check_newVersion:
//                //toast("点击更新");
//                 checkPermissionUpdate.updateVersion();
                checkVersion();
                break;
            case R.id.mine_about:
                Intent aboutIntent = new Intent(getActivity(), AboutActivity.class);
                startActivity(aboutIntent);
                break;
            case R.id.mine_telephone_ll:
                showDialog(1);
                break;
        }
    }

    private Dialog updateDialog = null;

    private void checkVersion() {
        if (isUpdate) {
            manager = new DownloadManager(getActivity(), versionInfo);
            manager.notifyPermission(true);
            manager.setAction(new DownloadManager.OnDialogAction() {

                @Override
                public void onPositiveButtonClick() {
                    manager.onUpdateAction(getActivity().getSupportFragmentManager());
//                    isUpdate = true;
                }

                @Override
                public void OnNegativeButtonClick() {
//                    isUpdate = false;

                }

                @Override
                public void onUploadFailed() {
                    toast("更新失败");
                }
            });
            // 检查软件更新
            if (updateDialog != null && updateDialog.isShowing()) {
                updateDialog.dismiss();
            }
//                isForce = false;

            boolean b = manager.checkUpdate(VersionUtil.getVersionCode(getActivity()),
                    versionInfo.getVersionCode(), false, versionInfo.getDescription(), getActivity().getSupportFragmentManager());
            if (!b) {
//                if (show_type == 1) {
                toast("已经更新到最新版本啦！");
//                }
            }

        }

    }

    /**
     * 对应点击事件
     *
     * @param view
     */
    @OnClick(value = {R.id.mine_login_subscribe, R.id.mine_login_collection, R.id.mine_login_invitation_number, R.id.mine_login_history})
    public void loginClick(View view) {
        switch (view.getId()) {
            case R.id.mine_login_subscribe:
                // String url = (String) SharedPreferencesUtil.getParam(getContext(), SUBSCRIBE_KEY, "");
                Intent intent = new Intent(getContext(), MySubscribeActivity.class);
                intent.putExtra(BaseActivity.EX_TYPE, 2);
                //intent.putExtra(BaseActivity.EX_URL, "url");
                startActivity(intent);

                break;
            case R.id.mine_login_collection:
                Intent collectionIntent = new Intent(getActivity(), MyCollectionActivity.class);
                startActivity(collectionIntent);
                break;
            case R.id.mine_login_invitation_number:
                if (UserManager.isLoginS()) {
                    Intent invitationIntent = new Intent(getActivity(), InvitationCodeActivity.class);
                    startActivityForResult(invitationIntent, REQUEST_CODE_INVITATION);
                } else {
                    toLogin();
                }
                break;
            case R.id.mine_login_history:
                Intent historiesIntent = new Intent(getActivity(), HistoriesActivity.class);
                startActivity(historiesIntent);
                break;
        }
    }

    @OnClick(value = {R.id.mine_icon, R.id.mine_username})
    public void userLoginClick(View view) {
        if (isLogin(false)) {
            Intent intent = new Intent(getContext(), UserInfoActivity.class);
            startActivityForResult(intent, REQUEST_CODE_INFO);
        } else {
            toLogin();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_top_edit:
                showDialog(0);
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            JPushInterface.init(getContext().getApplicationContext());
            JPushInterface.resumePush(getContext());
            JPushInterface.setAlias(getContext(), 0, "scgc2_0");
            SharedPreferencesUtil.setParam(getContext(), "PUSH_KEY", true);
            JLog.e(JPushInterface.getRegistrationID(getContext()));
            ;
        } else {
            JPushInterface.stopPush(getContext());
            SharedPreferencesUtil.setParam(getContext(), "PUSH_KEY", false);
        }
    }

    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            parseWhat(msg.what);
        }
    };

    private void parseWhat(int what) {
        if (what == Constances.BIG_FONT) {
            font_tv.setText("大");
        } else if (what == Constances.MID_FONT) {
            font_tv.setText("中");
        } else if (what == Constances.SMALL_FONT) {
            font_tv.setText("小");
        } else if (what == ShowDiaFragment.LOGINOUT_TAG) {
            UserManager.getInstance().setUser(getContext(), null);
            UserManager.getInstance().delUserCache(getContext());
            checkUser();
        } else if (what == ShowDiaFragment.PHONE_TAG) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + getString(R.string.mine_telephone_number)));
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                toast(R.string.failed_to_phone);
            }
        }
    }

    private void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, REQUEST_CODE_LOGIN);
    }

    private synchronized void showFontDialog() {
//        if (fontSizeDiaFragment == null) {
        fontSizeDiaFragment = new FontSizeDiaFragment();
//        }
//        if (fontSizeDiaFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName(), 50)) {
//            return;
//        }
        fontSizeDiaFragment.setCallBack(callBack);
        FragmentManager fm = getChildFragmentManager();
        fontSizeDiaFragment.show(fm, FONT_TAG);
        fm.executePendingTransactions();
    }

    private boolean isLogin(boolean isLogin) {
        return UserManager.getInstance().isLogin();
    }

    private void showDialog(int type) {
//        if (showDiaFragment == null) {
        showDiaFragment = new ShowDiaFragment();
//        }
        showDiaFragment.setCallBack(callBack);
        showDiaFragment.setType(type);
        showDiaFragment.show(getActivity().getSupportFragmentManager(), SHOW_TAG);
    }
}
